package com.zbkj.crmeb.store.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.crmeb.core.exception.CrmebException;
import com.zbkj.crmeb.store.dao.HomeStylePreviousDao;
import com.zbkj.crmeb.store.model.HomeStyle;
import com.zbkj.crmeb.store.model.HomeStylePrevious;
import com.zbkj.crmeb.store.service.HomeStylePreviousService;
import com.zbkj.crmeb.store.service.HomeStyleService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class HomeStylePreviousServiceImpl extends ServiceImpl<HomeStylePreviousDao, HomeStylePrevious> implements HomeStylePreviousService {
    @Autowired
    HomeStyleService homeStyleService;

    public Boolean savePrevious(Boolean save, Integer merId){

        //不保存直接删除
        if (!save){
            return homeStyleService.remove(Wrappers.<HomeStyle>lambdaQuery()
                    .eq(HomeStyle::getMerId, merId)
                    .isNull(HomeStyle::getActivityId));
        }

        //查询之前的模板配置
        List<HomeStyle> list = homeStyleService.list(Wrappers.<HomeStyle>lambdaQuery()
                .eq(HomeStyle :: getMerId, merId)
                .isNull(HomeStyle::getActivityId)
                .orderByAsc(HomeStyle :: getSort)
        );

        List<HomeStylePrevious> homeStylePreviousList = new ArrayList<>();
        //对象复制
        for (HomeStyle homeStyle : list){
            HomeStylePrevious homeStylePrevious = new HomeStylePrevious();
            BeanUtils.copyProperties(homeStyle, homeStylePrevious);

            homeStylePreviousList.add(homeStylePrevious);
        }

        //删除之前的模板配置
        homeStyleService.remove(Wrappers.<HomeStyle>lambdaQuery()
                .eq(HomeStyle::getMerId, merId)
                .isNull(HomeStyle::getActivityId));

        //先删除上次保存的数据
        this.remove(Wrappers.<HomeStylePrevious>lambdaQuery()
                .eq(HomeStylePrevious::getMerId, merId));

        return this.saveOrUpdateBatch(homeStylePreviousList);
    }

    @Override
    public Boolean restoreStyle(Integer merId) {

        //查询上次的模板内容
        List<HomeStylePrevious> list = this.list(Wrappers.<HomeStylePrevious>lambdaQuery()
                .eq(HomeStylePrevious::getMerId, merId)
                .orderByAsc(HomeStylePrevious::getSort));

        List<HomeStyle> homeStyles = new ArrayList<>();
        //对象复制
        for (HomeStylePrevious homeStylePrevious : list){
            HomeStyle homeStyle = new HomeStyle();
            BeanUtils.copyProperties(homeStylePrevious, homeStyle);

            homeStyles.add(homeStyle);
        }

        //将现在的模板进行保存
        savePrevious(true, merId);

        //还原上次的模板
        return homeStyleService.saveOrUpdateBatch(homeStyles);
    }
}
